package com.ruoyi.project.system.weixinUtil.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ruoyi.project.system.weixinUtil.domain.AccessToken;
import com.ruoyi.project.system.weixinUtil.service.CoreService;
import com.ruoyi.project.system.weixinUtil.utils.CommonUtil;
import com.ruoyi.project.system.weixinUtil.utils.SignUtil;
import com.ruoyi.project.system.wxAccesstoken.domain.WxAccesstoken;
import com.ruoyi.project.system.wxAccesstoken.service.IWxAccesstokenService;
import com.ruoyi.project.system.wxAccesstoken.service.WxAccesstokenServiceImpl;


@Controller
@Component("WeixinServlet")
@RequestMapping("/weixinServlet")
public class weixinServlet extends HttpServlet {
	
	@Autowired
	private IWxAccesstokenService wxAccesstokenService;
	@Autowired
	private CoreService coreService;
	
	private static final long serialVersionUID = 4323197796926899691L;
	private static final String APPID = "wxf0f67fb7b9f5cd4b";
	private static final String APPSECRET = "ce52dee6aaba352778f19bff4b3f35d5";
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
	/**
	 * 请求校验(确认请求来自微信服务器)
	 */
	@GetMapping
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}
	
	/*@GetMapping("/Certification")
	public void Certification(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();
        
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
        
        out.close();
        out = null;
	}*/
	
	/**
	 * 更新获取access_token
	 */
	public void access_token() {
		WxAccesstoken accessToken = CommonUtil.getToken(APPID, APPSECRET);
		//取出第一个，直接替换
		WxAccesstoken wxaccessToken = wxAccesstokenService.selectWxAccesstokenById(1);
		wxaccessToken.setToken(accessToken.getToken());
		wxaccessToken.setExpiresIn(accessToken.getExpiresIn());
		wxAccesstokenService.updateWxAccesstoken(wxaccessToken);
	}
	
	
	/**
     * 处理微信服务器发来的消息
     */
	@PostMapping
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 接收参数:微信加密签名、时间戳、随机数
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");

		PrintWriter out = response.getWriter();
		// 请求校验
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			// 调用核心服务类接收处理请求
			String respXml = coreService.processRequest(request);
			out.print(respXml);
		}

		out.close();
		out = null;
    }
}
